package com.otitan.la.forest.industry.utils;

import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Maps;
import com.otitan.webapp.framework.basepro.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 当前类作用描述
 * @Author: xiazw
 * @CreateDate: 2020/8/18 16:14
 */
@Slf4j
public class FileUtil {

    /**
     * excel表格直接下载
     */
    public static void exportExcelByDownload(Workbook wb, HttpServletResponse response, String fileName) {

        // 设置response的Header
        setResponseContentDisposition(response, fileName);
        response.setContentType("application/octet-stream");
        try {
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

//        OutputStream stream = new BufferedOutputStream(response.getOutputStream());

        //输出流开始写出文件（FileUtils是Apache下的工具类可以直接调用）
//        stream.write(bytes);
        //刷新流
//        stream.flush();

    }

    /**
     * @Description:    设置response的Header
     * @Author:        wangqingsong
     * @exception          [response, fileName]
     * @return             void
     * @CreateDate:     2020/10/19 17:19
     */
    public static void setResponseContentDisposition(HttpServletResponse response, String fileName) {
        // 清空response
        response.reset();

        // 创建显示内容
        StringBuilder contentDisposition = new StringBuilder("attachment;");
        // 如果附件不为null;
        if (fileName != null) {
            // 通过UTF8字符以及URL方式来编码文件名
            String filedisplay = fileName;
            try {
                filedisplay = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Ignore
            }
            // 添加标准文件名
            contentDisposition.append("filename=").append(fileName).append(";");
            // 添加UTF8格式名
            // 主要为了防止部分浏览器下的文件名乱码（参见https://tools.ietf.org/html/rfc6266）
            contentDisposition.append("filename*=utf-8''").append(filedisplay);
        }
        // 输出文件名
        response.addHeader("Content-Disposition", contentDisposition.toString());
    }

    /**
     * 将日期转换成字符串
     * @param date
     * @return
     */
    public static String dateToString(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = simpleDateFormat.format(date);
        return str;
    }


    /**
     * 将map中的null转变成空值
     * @param map
     * @return
     */
    public static Map<String, Object> nullToEmpty(Map<String, Object> map) {
        Set<String> set = map.keySet();
        if(set != null && !set.isEmpty()) {
            for(String key : set) {
                if(map.get(key) == null) { map.put(key, ""); }
            }
        }
        return map;
    }

    /**
     * 将对象装换为map
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key+"", beanMap.get(key));
            }
        }
        return map;
    }



    public static String uploadFile(String bashPath, MultipartFile file) {
        // 创建文件夹
        String fileNewPath = mkdirs(bashPath);

        try {
            String fileName = file.getOriginalFilename();
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
            UUID uuid = UUID.randomUUID();
            String fileNewName = uuid + fileSuffix;
            File dest = new File(fileNewPath + fileNewName);
            file.transferTo(dest);
            log.debug("【文件上传】文件路径：{}", dest.getPath());
            return dest.getPath();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【文件失败】错误信息：{}", e.getMessage());
        }
        return null;
    }

    public static String mkdirs(String bashPath) {
        Date date = new Date();
        String dateStr = DateUtil.parseDate(date, DateUtil.YYYYMMDD);

        // 文件相对路径
        String path = dateStr.substring(0, 4) + File.separator
                + dateStr.substring(0, 6) + File.separator
                + dateStr.substring(0, 8) + File.separator;

        String fileNewPath = bashPath + path;
        File dir = new File(fileNewPath);

        boolean isSuccessMakeDir = false;
        if (!dir.exists()) {
            try {
                isSuccessMakeDir = dir.mkdirs();
                if (!isSuccessMakeDir) {
                    log.error("文件创建失败：{}" + path);
                    throw new BusinessException("创建文件夹失败！");
                }
            } catch (Exception e) {
                log.error("文件创建失败：{}" + path);
                throw new BusinessException("创建文件夹失败！");
            }
        }
        return fileNewPath;
    }

    public static final String enterFileName = "六安龙头企业导入模板-" + DateUtil.getNowDateStr() + ".xls";
    public static final String outputStatisFileName = "林业产业产值统计导入模板-" + DateUtil.getNowDateStr() + ".xls";
    public static final String enterExcelPath =  "/excel/六安龙头企业导入模板.xls";
    public static final String outputStatisExcelPath =  "/excel/六安林业产值导入模板.xls";


    /**
   * 下载导入的excel模板
   * @author Sunke
   * @param [response]
   * @return void
   * @exception
   * @date 2020/10/20 0020 17:22
   */
    public static void importFile(HttpServletResponse response,String fileName,String excelPath) {

        try {
            // 文件的存放路径
            InputStream inStream = ExcelUtil.class.getResourceAsStream(excelPath);
            // 设置输出的格式
            setResponseContentDisposition(response, fileName);
            response.setContentType("application/octet-stream");
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
